<?php
/**
 * Created by JetBrains PhpStorm.
 * User: ishowshao
 * Date: 12-12-11
 * Time: 下午9:15
 * To change this template use File | Settings | File Templates.
 */
require 'config.php';

function thumb($src, $dst, $type) {
    if ($type == 'jpg') {
        $im = imagecreatefromjpeg($src);
    } else {
        $im = imagecreatefrompng($src);
    }
    $x = imagesx($im);
    $y = imagesy($im);

    if ($y > 320) {
        $w = 320;
        $h = $y * 320 / $x;
        $thumb = imagecreatetruecolor($w, $h);
        imagecopyresized($thumb, $im, 0, 0, 0, 0, $w, $h, $x, $y);
        imagejpeg($thumb, $dst, 95);
    }
}

session_start();
if (empty($_SESSION['username'])) {
    exit;
}

date_default_timezone_set('PRC');
$data = array(
    'time' => time(),
    'twitter' => '',
    'photos' => array(),
    'creator' => $_SESSION['username'],
);

if (isset($_POST['twitter'])) {
    $data['twitter'] = trim($_POST['twitter']);
}

$types = array(
    'image/jpeg' => 'jpg',
    'image/png' => 'png',
);

$time = time();
if (isset($_FILES['photo'])) {
    $photos = $_FILES['photo'];
    if (is_array($photos['error'])) {
        foreach ($photos['error'] as $index => $error) {
            if ($error == 0 && isset($types[$photos['type'][$index]])) { //没有错误而且文件类型在白名单
                $photoId = md5($photos['tmp_name'][$index] . $time);
                $ext = $types[$photos['type'][$index]];
                $photoName = $photoId . '.' . $ext;
                $path = './data/photos/' . $photoName;
                move_uploaded_file($photos['tmp_name'][$index], $path);
                //创建缩略图
                thumb($path, './data/thumbs/' . $photoName, $ext);
                array_push($data['photos'], $photoName);
            }
        }
    }
}

$dataFile = DATA_FILE;
if (!file_exists($dataFile)) {
    file_put_contents($dataFile, '[]');
}

if ($data['twitter'] == '' && count($data['photos']) == 0) {
    exit('<script>parent.onUploaded();</script>');
}

$all = json_decode(file_get_contents($dataFile), true);
array_push($all, $data);
file_put_contents($dataFile, json_encode($all));

echo '<script>parent.onUploaded(' . json_encode($data) . ');</script>';
